$(document).ready(function () {
    Carousel.memo = {"enumName": "programTypeData", "listName": "mockData", fatherId: 0,
        platformRefer: "platformRefer",
        platSettings: "platSettings",
        platforms: "platforms",
        "getChannel": "getChannel"
    }
    Carousel.ErrorMsg = {
        PPS_CLIENT_MSG: "该专辑在PPS端没有上线，但会在PPS平台播出，是否确认添加？",
        PPS_REGION_MSG: "该专辑在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？",
        QIYI_CLIENT_MSG: "该专辑在QIYI端没有上线，但会在QIYI平台播出，是否确认添加？",
        QIYI_REGION_MSG: "该专辑在QIYI端有地域播控，但会在QIYI平台全地域播出，是否确认添加？"
    }
    Carousel.lock = {flag: false};

    Carousel.Dao = (function () {
        var cache = {};

        function getDataByName(targetName) {
            var responseData = Carousel.ajaxManager.findResponseData(targetName);
            return responseData;
        }

        function getChannel() {
            return getDataByName(Carousel.memo.getChannel).data;
        }

        function liveProgramType() {
            return getDataByName(Carousel.memo.liveProgramType);
        }

        function getPlatformType() {
            return getDataByName(Carousel.memo.platforms)
        }

        function getPlatformRefer() {
            return getDataByName(Carousel.memo.platformRefer)
        }

        function getPlatSettings() {
            return getDataByName(Carousel.memo.platSettings)
        }

        function getSearchParamsBySettings() {
            var response = getPlatSettings();
            if (response == null) {
                console.log("[getSearchParamsBySettings] setting error");
                return {};
            }
            var entity = response.data;
            var params = {};
            if (entity.checkPublishType == 1) {
                params["filter_EQI_pagePublishStatus"] = 1;
            }
            if (entity.checkCopyRightType == 1) {
                params["filter_GTI_copyrightOwnerId"] = 0;
            }
            if (entity.checkBossType == 0) {
                params["filter_INI_isPurchase"] = "0,-100";
            } else if (entity.checkBossType == 1) {
                params["filter_INI_isPurchase"] = "1,2";
            }
            var platformTypeResponse = Carousel.Dao.getPlatformType();
            $.each(platformTypeResponse.data, function (i, element) {
                //   params["region_" + element.val] = 0;
                if (entity.regionLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["region_" + element.val] = 1;
                }
            });
            var platformReferResponse = Carousel.Dao.getPlatformRefer();
            $.each(platformReferResponse.data, function (i, element) {
                //   params["filter_EQI_" + element.val] = 0;
                if (entity.onlineLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["filter_EQI_" + element.val] = 1;
                }

            });
            console.log(" params:" + JSON.stringify(params))
            return params;
        }

        function getFromCache(dataKey) {
            return cache[dataKey]
        }

        function putToCache(dataKey, data) {
            cache[dataKey] = data
        }

        return {
            getChannel: getChannel,
            liveProgramType: liveProgramType,
            getPlatformType: getPlatformType,
            getPlatformRefer: getPlatformRefer,
            getPlatSettings: getPlatSettings,
            getFromCache: getFromCache,
            putToCache: putToCache,
            getSearchParamsBySettings:getSearchParamsBySettings
        }

    })();
    Carousel.Formatter = (function () {
        function quickDateFormat(startTime) {
            return startTime.getFullYear() + "-" +
                (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
        }

        function reutrnNull() {
            // return "unknown"
            return "";
        }

        function formatDate(myDate) {
            var year = myDate.getFullYear();
            var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
            var day = ("0" + myDate.getDate()).slice(-2);
            var h = ("0" + myDate.getHours()).slice(-2);
            var m = ("0" + myDate.getMinutes()).slice(-2);
            var s = ("0" + myDate.getSeconds()).slice(-2);
            return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
        }

        function getFormatCopyRightEndTime(checkValue) {
            if (checkValue == null) {
                return reutrnNull();
            }
            if (typeof( checkValue ) == "string") {
                return checkValue;
            }
            if (checkValue <= 0) {
                return "---";
            } else {
                var date = new Date();
                date.setTime(parseInt(checkValue))
                return  formatDate(date);
            }
        }

        function getFormatPurchase(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            switch (checkValue) {
                case 0:
                case -100:
                    return "免费";
                case 1:
                    return "收费";
                default:
                    return checkValue + ""
            }
        }

        function getFormatPublishStatus(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            switch (checkValue) {
                case 0:
                    return "未发布";
                case 1:
                    return "已发布";
                case 2:
                    return "页面下线";
                case 3:
                    return "页面备用"
                default:
                    return checkValue + "";
            }
        }

        function getTemplate(item) {
            var formatArr = [];
            formatArr.push('<span class="contract-width100">' + item["id"] + '</span>');
            formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
            formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
            formatArr.push('<span class="contract-width120">' + getFormatCopyRightEndTime(item.copyrightEndTime) + '</span>');
            formatArr.push('<span class="contract-width80">' + getFormatPurchase(item.isPurchase) + '</span>');
            formatArr.push('<span class="contract-width80">' + getFormatPublishStatus(item.pagePublishStatus) + '</span>');
            if (item["qipuPlatformData"] != null && item["qipuPlatformData"].length > 0) {
                return  '<div class="contract-item" style="color: red">' + formatArr.join("") + '</div>';
            } else if (item["qipuRegionData"] != null && item["qipuRegionData"].length > 0) {
                return  '<div class="contract-item" style="color: #ffa800">' + formatArr.join("") + '</div>';
            }
            return '<div class="contract-item">' + formatArr.join("") + '</div>';
        }

        return {
            copyRight: getFormatCopyRightEndTime,
            publishStatus: getFormatPublishStatus,
            purchase: getFormatPurchase,
            getTemplate: getTemplate,
            quickDateFormat: quickDateFormat,
            formatDate: formatDate
        }
    })();
    Carousel.Validate = (function () {
        var reg1 = /^\d+$/;
        var reg3 = /^[1-9]\d*$/;
        var reg2 = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;

        function checkNum(checkString) {
            return reg1.test(checkString)
        }

        function checkPositive(checkString) {
            return reg3.test(checkString)
        }

        function checkDateFormat(checkString) {
            return reg2.test(checkString)
        }

        function defaultHandler(msg) {
            showTips({content: msg});
        }

        function batchCheck(checkArr) {
            if (checkArr == null) {
                checkArr = [];
            }
            if (checkArr.length == 0) {
                return true;
            }
            var flag = false;
            $.each(checkArr, function (index, checkData) {
                flag = baseCheck(checkData);
                if (!flag) {
                    return false;
                }
            })
            return flag;
        }

        function baseCheck(checkData) {
            var flag = false;
            if (!(checkData.value instanceof Array)) {
                checkData.value = [checkData.value];
            }
            if (!(checkData.error instanceof Array)) {
                checkData.error = [checkData.error];
            }
            if (checkData.handler == null) {
                checkData.handler = defaultHandler;
            }

            $.each(checkData.value, function (index, checkValue) {
                switch (checkData.type) {
                    case "date":
                        flag = checkDateFormat(checkValue);
                        break;
                    case "not_empty":
                        flag = checkValue != null && checkValue != "";
                        break;
                    case "eq":
                        flag = checkValue == checkData.other;
                        break;
                    case "ne":
                        flag = checkValue != checkData.other;
                        break;
                    case "gt":
                        flag = checkValue > checkData.other;
                        break;
                    case "ge":
                        flag = checkValue >= checkData.other;
                        break;
                    case "lt":
                        flag = checkValue < checkData.other;
                        break;
                    case "le":
                        flag = checkValue <= checkData.other;
                        break;
                    case "positive":
                        flag = checkPositive(checkValue)
                        break;
                    case "number":
                        flag = checkNum(checkValue)
                        break;
                    case "endsWith":
                        flag = checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                        break;
                    default :
                        break;
                }
                if (!flag) {
                    var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                    checkData.handler(hint);
                    return false;
                }
            })
            return flag
        }

        return {
            baseCheck: baseCheck,
            batchCheck: batchCheck,
            checkNum: checkNum
        }
    })();
    Carousel.Task = (function () {

        function platSettingsTask(channelId) {
            return {
                regName: Carousel.memo.platSettings,
                options: {
                    url: Carousel.urlConfig.platSettingsGetUrl,
                    type: "post",
                    data: {channelId: channelId},
                    dataType: "json",
                    success: function (data) {
                        console.log(Carousel.memo.platSettings + ":" + data.code);
                    }
                }
            }
        }

        function getLiveProgramType() {
            return {
                regName: Carousel.memo.enumName,
                options: {
                    type: "get",
                    url: Carousel.urlConfig.configs,
                    dataType: "json",
                    data: {type: Carousel.memo.enumName}
                }
            }
        }

        function platformsTask() {
            return {
                regName: Carousel.memo.platforms,
                options: {
                    url: Carousel.urlConfig.configs,
                    type: "get",
                    data: {type: "PlayPlatform"},
                    dataType: "json",
                    success: function (data) {
                        console.log(Carousel.memo.platforms + ":" + data.code);
                    }
                }
            }
        }

        function getPlatformReferTask() {
            return {
                regName: Carousel.memo.platformRefer,
                options: {
                    url: Carousel.urlConfig.configs,
                    type: "get",
                    data: {type: "PlatformRefer"},
                    dataType: "json",
                    success: function (data) {
                        console.log(Carousel.memo.platformRefer + ":" + data.code);
                    }
                }
            }
        }

        function getCheckUrl(qipuId) {
            return Carousel.urlConfig.getQiPuBaseUrl(qipuId);
        }

        function sendAddRuleTaskCallFunc(data) {
            $("#carouselAutoRuleView").find("button[name=addRule]").removeAttr("disabled");
            showTips({content: data.msg});
            if (data.code == "A00000") {
                Carousel.EventManager.resetEvent();
                Carousel.Grid.fillRuleListGrid();
            }
        }

//        function sendDelRuleTaskCallFunc(data) {
//            showTips({content: data.msg});
//            if (data.code == "A00000") {
//                Carousel.Grid.fillRuleListGrid();
//            }
//        }




        function sendGetTotalNumTask(entityId) {
            var params = Carousel.Dao.getSearchParamsBySettings();
            //filter_EQL_albumId: entityId,
            params["filter_EQL_albumId"] = entityId;
            params["filter_GTL_qipuId"] = 0;
            params["filter_GEL_duration"] = 60000;
            params["filter_EQI_contentType"] = 1;
            params["t"] = 0;
            params["page.order"] = "asc,asc";
            params["page.orderBy"] = "videoOrder,createTime";
            params["page.pageSize"] = 1;

            var requestData = {url: Carousel.Constant.thirdUrl_apis_search_area_url, type: "get",
                params: params,
                needCookie: true};

            return {
                regName: "sendGetTotalNumTask",
                options: {
                    url: Carousel.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        $("input[name=actualNum]").val(data.data.totalCount);
                    },
                    error: function (data) {
                        console.log("请求失败:" + JSON.stringify(data));
                        $("input[name=actualNum]").val(0);
                    }
                }
            }
        }

        function sendCheckTask(qipuId) {
            var url = getCheckUrl(qipuId);
            var requestData = {url: url, type: "get", needCookie: true};
            return {
                regName: "sendCheckTask",
                options: {
                    url: Carousel.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        if (data != null && data.hasOwnProperty("episode_summary")) {
                            $("input[name=actualNum]").val(data["episode_summary"].length)
                        } else {
                            $("input[name=actualNum]").val();
                        }
                    },
                    error: function (data) {
                        console.log("data" + JSON.stringify(data));
                    }
                }
            }
        }

        function checkForQipuDataTask() {
            return {
                regName: "checkForQipu",
                options: {
                    url: Carousel.urlConfig.redirect,
                    dataType: "json",
                    type: "post"
                },
                handler: function (options) {
                    console.log(options.acceptArr);
                    var playControlArr = null;
                    var checkPlatforms = Carousel.Dao.getPlatformType().data;
                    var originalArr = Carousel.Dao.getFromCache("originalArr");
                    $.each(options.acceptArr, function (i, element) {
                        var original = originalArr[element.nodeIndex ];
                        if (element.responseData == null) {
                            original.illegal = true;
                            return true;
                        }
                        playControlArr = element.responseData["access_play_control"];
                        if (null == playControlArr && ( null == element.responseData["available_status"] || "OFFLINE_COPYRIGHT" === element.responseData["available_status"])) {
                            original.illegal = true;
                            return true;
                        }
                        if ($.isArray(playControlArr)) {
                            var temp = {};
                            $.each(playControlArr, function (index, elementChild) {
                                var platformObject = decodePlayPlatform(elementChild);
                                if (platformObject.platName != null) {
                                    temp[platformObject.platName] = platformObject;
                                }
                            })
                            original.controlObj = temp
                            var qipuPlatformData = [];
                            var qipuRegionData = [];
                            var hintMsgObj = {
                                missQIYIClient: false,
                                missPPSClient: false,
                                missQIYIRegion: false,
                                missPPSRegion: false
                            };
                            $.each(checkPlatforms, function (index, element) {
                                var ppsFlag = element.val.indexOf("PPS") !== -1;
                                if (!temp.hasOwnProperty(element.val) || temp[element.val].status != "online") {
                                    qipuPlatformData.push(element.val)
                                    if (ppsFlag) {
                                        hintMsgObj.missPPSClient = true;
                                    } else {
                                        hintMsgObj.missQIYIClient = true;
                                    }
                                }
                                if (temp.hasOwnProperty(element.val) && temp[element.val].locationArr.length > 0) {
                                    qipuRegionData.push(key);
                                    if (ppsFlag) {
                                        hintMsgObj.missPPSRegion = true;
                                    } else {
                                        hintMsgObj.missQIYIRegion = true;
                                    }
                                }
                            });
                            original["qipuPlatformData"] = qipuPlatformData;
                            original["qipuRegionData"] = qipuRegionData;
                            original["hintMsgObj"] = hintMsgObj;
                            console.log(element.responseData["id"] + "| qipuPlatformData : " + JSON.stringify(original["qipuPlatformData"]));
                            console.log(element.responseData["id"] + "| qipuRegionData: " + JSON.stringify(original["qipuRegionData"]));
                            console.log(element.responseData["id"] + "| hintMsgObj: " + JSON.stringify(original["hintMsgObj"]));
                        }

                        // TW
                        var channelbase = Carousel.Dao.getChannel();
                        if(channelbase != null && channelbase['type'] == 11) {
                            localbaseArr = element.responseData['local_base'];
                            if(localbaseArr != null) {
                                $.each(localbaseArr, function(index, local) {
                                    if(local['language'] == 'zh_TW' && local['display_name'] != null) {
                                        original['label'] = local['display_name'];
                                    }
                                })
                            }
                        }

                        console.log('haha');

                    });
                    Carousel.lock.flag = false;
                }
            }
        }

        function decodePlayPlatform(elementChild) {
            var locationControl = null;
            var platformObject = {platName: null, locationArr: []}
            platformObject.platName = elementChild["play_platform"];
            platformObject.status = 'online';
            if (elementChild["default_control"] != null) {
                if ("ONLINE" != elementChild["default_control"]["availabe_status"]) {
                    platformObject.status = "offline";
                }
            }
            if ($.isArray(elementChild["region_control"])) {
                $.each(elementChild["region_control"], function (indexRegion, regionElement) {
                    if ($.isArray(regionElement["location"])) {
                        $.each(regionElement["location"], function (j, child) {
                            if(child.hasOwnProperty("province_id")){
                                if (child["province_id"] != 95 && child["province_id"]  != 148 && child["province_id"]  != 228) {
                                    locationControl = regionElement["location_control"];
                                    if (locationControl != null && "ONLINE" != locationControl["availabe_status"]) {
                                        platformObject.locationArr.push(child["province_id"]);
                                        console.log("break regionElement location");
                                    }
                                }
                            }
                        })
                    }
                })
            }
            return platformObject;
        }

        function sendAddRuleTask(sendObj) {
            return {
                regName: "sendAddRuleTask",
                options: {
                    url: Carousel.urlConfig.carouselRuldAddUrl,
                    type: "post",
                    dataType: "json",
                    data: sendObj,
                    success: function (data) {
                        sendAddRuleTaskCallFunc(data);
                    },
                    error: function (data) {
                        console.log("data" + JSON.stringify(data));
                        $("#carouselAutoRuleView").find("button[name=addRule]").removeAttr("disabled");
                    }
                }
            }
        }

        return {
            sendAddRuleTask: sendAddRuleTask,
            //    sendDelRuleTask: sendDelRuleTask,
            sendCheckTask: sendCheckTask,
            sendGetTotalNumTask: sendGetTotalNumTask,
            checkForQipuDataTask: checkForQipuDataTask,
            platSettingsTask: platSettingsTask,
            platformsTask: platformsTask,
            getPlatformReferTask: getPlatformReferTask,
            getLiveProgramType: getLiveProgramType
        }
    })()


    Carousel.DialogManager = (function () {
        var doHandler = null;

        function initLoadLegoDlg() {
            $("#loadLegoMessage").dialog({
                title: "数据加载",
                autoOpen: false,
                width: 300,
                modal: true,
                dialogClass: 'alert',
                resizable: false
            });
        }

        function initCopyRightDlg() {
            $("#notifyCopyRightDlg").dialog({
                title: "版权到期提醒",
                autoOpen: false,
                width: 300,
                modal: true,
                dialogClass: 'alert',
                resizable: false,
                buttons: [
                    {
                        text: "继续",
                        click: function () {
                            $(this).dialog("close");
                            doHandler(true);
                        }
                    },
                    {
                        text: "中断",
                        click: function () {
                            $(this).dialog("close");
                            doHandler(false);
                        }
                    }
                ]
            });
        }

        function initDialogs() {
            initLoadLegoDlg();
            initCopyRightDlg();
            $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
        }

        function queryDlg(msg, divId, callback) {
            doHandler = function (flag) {
                if (typeof(callback) == "function") {
                    callback(flag);
                }
            }
            $("#" + divId).html(msg);
            $("#" + divId).dialog("open");
        }

        return {
            initDialogs: initDialogs,
            queryDlg: queryDlg
        }
    })();
    Carousel.Suggest = (function () {


        function fillAutoRuleDiv(selectElement) {
            Carousel.Grid.fillRuleView(selectElement);
        }


        function checkQipuPlatformControl(callback, ret) {
            if (Carousel.lock.flag) {
                return;
            }
            Carousel.lock.flag = true;
            var task = Carousel.Task.checkForQipuDataTask();
            var dataArr = [];
            var requestData = null;
            var currentTime = Date.now();
            Carousel.Dao.putToCache("originalArr", ret);
            $.each(ret, function (i, element) {
                requestData = {url: Carousel.urlConfig.getQiPuBaseUrl(element["id"]), type: "get"};
                dataArr.push({"request": JSON.stringify(requestData), timeSign: currentTime });
            });

            //   $("#loadLegoMessage").dialog("open");
            Carousel.ajaxManager.batchRequest(task.regName, task.options, dataArr, task.handler);
            var timerId = setInterval(function () {
                if (!Carousel.lock.flag) {
                    clearInterval(timerId);
                    //  $("#loadLegoMessage").dialog("close");
                    var filterArr = [];
                    $.each(ret, function (i, element) {
                        if (element.illegal === true) {
                            console.log("illegal:" + element.id);
                        } else {
                            filterArr.push(element)
                        }
                    })
                    callback.call(this, filterArr);
                }
            }, 1000)
            Carousel.ajaxManager.startLoad();
        }


        var defaultHeaderHtml = '<div class="contract-item" >' +
            '<span class="contract-width100">奇谱ID</span>' +
            '<span class="contract-width150">显示名称</span>' +
            '<span class="contract-width60">频道</span>' +
            '<span class="contract-width120">版权到期时间</span>' +
            '<span class="contract-width80">是否付费</span>' +
            '<span class="contract-width80">发布状态</span></div>';
        var albumSuggest = {

            options: {
                _beforeSuggest: function (callback) {
                    var task = Carousel.Task.platSettingsTask(Carousel.memo.fatherId);
                    Carousel.ajaxManager.removeTask( task.regName);
                    var ajaxData = task.options;
                    $.ajax({
                        type: ajaxData.type,
                        url: ajaxData.url,
                        dataType: ajaxData.dataType,
                        beforeSend: function (request) {
                            request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                        },
                        data: ajaxData.data,
                        success: function (data) {
                            Carousel.ajaxManager.push( task.regName , task.options, data ,false)
                            callback.call();
                        },
                        error:function(data) {
                            showTips({content: data.msg});
                        }
                    });
                    /*
                     var task = Carousel.Task.platSettingsTask(Carousel.memo.fatherId);

                     Carousel.ajaxManager.push( task.regName,task.options);
                     Carousel.ajaxManager.afterLoadComplete(callback);
                     Carousel.ajaxManager.startLoad();
                    * */
                },
                _doSuggest: function (request, response,param) {
                    var self = this,
                        options = self.options,
                        url = options.url,
                        getParam = null,
                        term = jfUtil.simplized($.trim(request.term)),
                        getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(self, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }
                    self._getSuggestData(url, options.method, param, $.proxy(self.options._handleResponse, self, request, response));
                },
                _handleResponse: function (request, response, data) {
                    var self = this,
                        options = self.options,
                        term = jfUtil.simplized($.trim(request.term)),
                        dataProcess = options.process,
                        ret = dataProcess.call(self, data, term);

                    ret = $.ui.autocomplete.filter(ret, term);

                    if (options.highlight) {
                        options.highlight.call(self, ret, self._displayKey, term);
                    }

                    self.result = ret;
                    if (ret.length > 0) {
                        checkQipuPlatformControl(response, ret);
                    }
                    //response
                },
                url: Carousel.urlConfig.redirect,
                source: function (request, response) {
                    var self = this,
                        options = self.options,
                        term = jfUtil.simplized($.trim(request.term)),
                        url = null,
                        getParam = null,
                        param = {};
                    //    self._handleResponse = self.options._handleResponse;
                    if (!term) {
                        return null;
                    }

                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }

                    param = $.extend(true, options.otherParam, param);

                    if ($.isFunction(self.options._beforeSuggest)) {
                        self.options._beforeSuggest.call(self, function () {
                            self.options._doSuggest.call(self,request, response,param)
                        })
                    } else {
                        self.options._doSuggest.call(self,request, response,param)
                    }
                },


                method: "post",
                multiple: false,
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                select: function (event, object) {
                    var msg = [];
                    var self = this;
                    if (object.item.hintMsgObj.missPPSClient) {
                        msg.push(Carousel.ErrorMsg.PPS_CLIENT_MSG);
                    }
                    if (object.item.hintMsgObj.missQIYIClient) {
                        msg.push(Carousel.ErrorMsg.QIYI_CLIENT_MSG);
                    }
                    if (object.item.hintMsgObj.missPPSRegion) {
                        msg.push(Carousel.ErrorMsg.PPS_REGION_MSG);
                    }
                    if (object.item.hintMsgObj.missQIYIRegion) {
                        msg.push(Carousel.ErrorMsg.QIYI_REGION_MSG);
                    }

                    self.value = "";
                    if (msg.length > 0) {
                        SystemDialog.queryConfirm(msg.join("<br>"), function (flag) {
                            if (flag === true) {
                                self.value = object.item.id + "";
                                fillAutoRuleDiv(object.item)
                            }
                        });
                    } else {
                        self.value = object.item.id + "";
                        fillAutoRuleDiv(object.item)
                    }
                    return false;
                },
                getParam: function (term) {
                    var currentTime = new Date().getTime();
                    var params =Carousel.Dao.getSearchParamsBySettings();
                    params["word"] = jfUtil.simplized(term);
                    params["size"] = 20;
                    params["type"] = "displayName";
                    var requestData = {url: Carousel.Constant.thirdUrl_album_area_url, type: "get", params: params, needCookie: true};
                    return {"request": JSON.stringify(requestData), timeSign: currentTime}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json == null) {
                        showTips({content: "获取接口数据失败"});
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }
                    var currentTime = new Date().getTime();
                    $.map(data, function (item) {
                        if (item["qipuId"] == null || item["qipuId"] == 0) {
                            return true;
                        }
                        itemData = {};
                        itemData[options.valueKey] = item["qipuId"];
                        itemData[options.labelKey] = item["displayName"];
                        itemData["channelName"] = item["channelName"];
                        itemData["copyrightBeginTime"] = item["copyright"] ? item["copyright"][0].copyrightBeginTime : null;
                        itemData["copyrightEndTime"] = item["copyright"] ? item["copyright"][0].copyrightEndTime : null;
                        itemData["isPurchase"] = item["isPurchase"];
                        itemData["pagePublishStatus"] = item["pagePublishStatus"];
                        itemData["entityId"] = item["entityId"];
                        itemData["totalNum"] = item["totalNumberOfEpisodes"]
                        itemData.hintMsgObj = item.hintMsgObj;
                        itemData["pageUrl"] = item["pageUrl"];
                        ret.push(itemData);
                    });
                    return ret;
                },
                template: function (item) {
                    return Carousel.Formatter.getTemplate(item)
                },
                header: defaultHeaderHtml
            }
        }
        var playListSuggest = {
            options: {
                source: Carousel.urlConfig.redirect,
                method: "post",
                multiple: false,
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },

                select: function (event, object) {
                    this.value = object.item.id + "";
                    fillAutoRuleDiv(object.item)
                    return false;
                },
                // PC网页iqiyi.com : 1
                // PC客户端:5
                // Pad客户端:2
                // 手机客户端:3
                // 手机网页端:15
                // 电视:4
                //  mini合作站:27
                getParam: function (owner, term) {
                    var requestData = {url: Carousel.Constant.thirdUrl_playlist_url, type: "get", params: {word: this.element.val(),
                        type: "displayName",
                        filter_GTI_totalCount: 0,
                        //   filter_MULTS_platform: "1,5,2,3,15,4,27",
                        filter_EQI_pagePublishStatus: 1 }, needCookie: true};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }
                    $.map(data, function (item) {
                        if (item["qipuId"] == null || item["qipuId"] == 0) {
                            return true;
                        }
                        itemData = {};
                        itemData[options.valueKey] = item["qipuId"];
                        itemData[options.labelKey] = item["name"];
                        itemData["channelName"] = item["channelName"] == null ? "" : item["channelName"];
                        itemData["copyrightEndTime"] = "";
                        itemData["isPurchase"] = "";
                        itemData["pagePublishStatus"] = item["pagePublishStatus"];
                        itemData["totalNum"] = item["totalCount"];
                        itemData["pageUrl"] = item["pageUrl"];
                        ret.push(itemData);
                    });
                    return ret;
                },
                template: function (item) {
                    return Carousel.Formatter.getTemplate(item)
                },
                header: defaultHeaderHtml
            }
        }

        function initSuggest() {
            $("input[name$=_album]").suggest(albumSuggest.options);
            $("input[name$=_playlist]").suggest(playListSuggest.options);
        }

        return{
            initSuggest: initSuggest
        }
    })()

    Carousel.EventManager = (function () {
        function bindEvent() {
            resetEvent();
            $("select[name$=frontSuggestType]").bind("change", function (event) {
                var $curTarget = $(event.currentTarget)
                var selectedValue = $curTarget.val();
                console.log("selectedValue")
                $curTarget.parent().find("span input").parent().hide();
                $curTarget.parent().find("span input[name$=_" + selectedValue + "]").parent().show();
                var viewDiv = $("#carouselAutoRuleView");
                viewDiv.find("div[tag=itemTime_div]").hide();
                if (selectedValue == "album") {
                    viewDiv.find("div[tag=follow_div]").show();
                } else if (selectedValue == "playlist") {
                    viewDiv.find("div[tag=follow_div]").hide();

                }
            })
            $("select[name=frontSuggestType]").change();
            $("select[name$=SuggestType]").parent().find("span input").show();
        }

        function initDateTimePicker() {
            var minDateTime = new Date();
            minDateTime.setTime(minDateTime.getTime() + 40 * 1000 * 60);
            $("input[name=startDate]").datetimepicker({

                sliderAccessArgs: { touchonly: false },
                minDateTime: minDateTime
            });
            $("input[name=startDate]").val(Carousel.Formatter.formatDate(minDateTime));
        }

        function resetEvent() {
            $("input[type=text]").val("");
            $("input[type=checkbox]").removeAttr("checked");
            $("input[type=checkbox]").removeAttr("disabled");
            Carousel.Grid.clearRuleView();
        }

        return {
            bindEvent: bindEvent,
            initDateTimePicker: initDateTimePicker,
            resetEvent: resetEvent
        }
    })();

    Carousel.Operation = (function () {
        var entity = this;
        this.entityPath = "";
        this.tableName = "";

        function ruleDel(entityId, fatherId, msg) {
            auth.getAuthData({tips: 1, url: '/epg/carousel_program_delete.html'}, function (rt) {
                if (rt) {
                    showTips({content: '很抱歉，您没有删除的权限!'})
                    return;
                }
                var message = '确认删除？';
                if (msg) {
                    message = msg;
                }
                SystemDialog.queryConfirm(message, function (flag) {
                    if (flag === true) {
                        $.ajax({
                            url: Carousel.urlConfig.carouselRuleDelUrl,
                            dataType: "json",
                            data: {ids: entityId, fatherId: fatherId},
                            beforeSend: function (request) {
                                request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                            },
                            type: "post",
                            success: function (data) {
                                showTips({content: data.msg})
                                if (data.code == "A00000") {
                                    $("#ruleList").trigger("reloadGrid")
                                }
                            }
                        })
                    }
                })
            })
        }

        function transToCheckKey(sendData) {
            var dataArr = [];
            dataArr.push(sendData.qipuId);
            dataArr.push(sendData.startNum);
            dataArr.push(sendData.repeatedStatus);
            dataArr.push(sendData.followedStatus);
            dataArr.push(sendData.followNum);
            dataArr.push(sendData.startTime);
            return dataArr.join("|")
        }

        function ruleCheckMulti(sendData) {
            var dataArr = $("#ruleList").jqGrid('getData');
            var uniqueKey = transToCheckKey(sendData);
            var findSamekey = false;
            $.each(dataArr, function (i, element) {
                if (transToCheckKey(element) == uniqueKey) {
                    findSamekey = true;
                    return false;
                }
            });
            return findSamekey;
        }

        function ruleAdd() {
            var parent = $("#carouselAutoRuleView");
            var element = Carousel.Grid.getLastSelectElement();
            if (element == null) {
                console.log("no element selected")
                return;
            }

            var checkArr = [];
            var sendObject = {};
            sendObject.fatherId = Carousel.memo.fatherId;
            sendObject.showName = element.value;
            sendObject.channelTag = element.channelName;
            sendObject.qipuId = element.id;
            //
            checkArr.push({value: sendObject.qipuId + "", error: "不允许手动修改对象奇谱Id", type: "eq", other: parent.find("input[name=_" + parent.find("select[name=frontSuggestType]").val() + "]").attr("data-id") })
            sendObject.startTime = parent.find("input[name=startDate]").val();
            checkArr.push({value: sendObject.startTime, error: "开始时间日期格式错误", type: "date"})
            checkArr.push({value: parent.find("input[name=actualNum]").val(), error: "奇谱没有实际数据", type: "positive"})
            if (parent.find("input[name=hour_itemTime]").val().length > 0) {
                checkArr.push({value: parent.find("input[name=hour_itemTime]").val(), error: "需要正整数", type: "positive"})
            }
            if (parent.find("input[name=min_itemTime]").val().length > 0) {
                checkArr.push({value: parent.find("input[name=min_itemTime]").val(), error: "需要正整数", type: "positive"})
            }
            if (parent.find("input[name=sec_itemTime]").val().length > 0) {
                checkArr.push({value: parent.find("input[name=sec_itemTime]").val(), error: "需要正整数", type: "positive"})
            }
            checkArr.push({value: parent.find("input[name=follow_num]").val(), error: "联播集数需要正整数", type: "positive"})
            //	是否循环(1：循环 2：不循环)
            sendObject.repeatedStatus = parent.find("input[name=check_repeat]").prop("checked") == true ? 1 : 2;
            sendObject.copyrightEndTime = "";

            var queryMsg = "";
            if (element.copyrightEndTime == -100) {
                sendObject.copyrightEndTime = "-100";
            } else if (element.copyrightEndTime != null && element.copyrightEndTime != "" && element.copyrightEndTime > 0) {
                sendObject.copyrightEndTime = Carousel.Formatter.copyRight(element.copyrightEndTime);
            }
            //epg 收费状态(1：免费 2：收费)
            sendObject.bossStatus = 1;
            if (element.isPurchase !== "") {
                sendObject.bossStatus = element.isPurchase === 1 ? 2 : 1
            }
            //epg 发布状态(1：未发布 2：已发布)
            sendObject.publishStatus = 2
            if (!Carousel.Validate.batchCheck(checkArr)) {
                console.log("interrupt case check Fail")
                return;
            }


            sendObject.itemTime = 0;
            //是否跟播(1：跟播 2：不跟播)
            sendObject.followedStatus = parent.find("input[name=check_follow]").prop("checked") == true ? 1 : 2;

            if (sendObject.followedStatus == 1 && sendObject.repeatedStatus == 1) {
                showTips({content: "暂时不支持跟播加循环的组合"});
                return;
            }

            if (sendObject.qipuId % 100 == 2) {
                sendObject.itemTime = 0;
                sendObject.followedStatus = 2;
            }
            sendObject.followNum = parseInt(parent.find("input[name=follow_num]").val());
            sendObject.totalNum = element.totalNum;
            sendObject.pageUrl = element.pageUrl;
            if (sendObject.pageUrl == null) {
                sendObject.pageUrl = "";
            }
            sendObject.actualNum = parseInt($("input[name=actualNum]").val());
            if (sendObject.followedStatus != 1 && sendObject.followNum > sendObject.actualNum) {
                showTips({content: "非跟播节目联播集数不能大于实际集数"})
                return;
            }
            //开始
            sendObject.startNum = 1;
            if (sendObject.actualNum < sendObject.totalNum && sendObject.followedStatus == 1) {
                sendObject.startNum = sendObject.actualNum - sendObject.followNum + 1;
                if (sendObject.startNum < 1) {
                    sendObject.startNum = 1
                }
            }

            var hasSame = ruleCheckMulti(sendObject)
            console.log("hasSame:" + hasSame);
            if (ruleCheckMulti(sendObject)) {
                showTips({content: "已经存在相同规则"})
                return;
            }

            var msg = [];
            if (element.hintMsgObj.missPPSClient) {
                msg.push(Carousel.ErrorMsg.PPS_CLIENT_MSG)
            }
            if (element.hintMsgObj.missQIYIClient) {
                msg.push(Carousel.ErrorMsg.QIYI_CLIENT_MSG);
            }
            if (element.hintMsgObj.missPPSRegion) {
                msg.push(Carousel.ErrorMsg.PPS_REGION_MSG);
            }
            if (element.hintMsgObj.missQIYIRegion) {
                msg.push(Carousel.ErrorMsg.QIYI_REGION_MSG);
            }
            if (msg.length > 0) {
                SystemDialog.queryConfirm(msg.join("<br>"), function (flag) {
                    if (flag === true) {
                        $("#carouselAutoRuleView").find("button[name=addRule]").prop("disabled", "disabled");
                        var task = Carousel.Task.sendAddRuleTask(sendObject)
                        Carousel.ajaxManager.push(task.regName, task.options, null, true);
                        Carousel.ajaxManager.startLoad();
                    }
                })
            } else {
                $("#carouselAutoRuleView").find("button[name=addRule]").prop("disabled", "disabled");
                var task = Carousel.Task.sendAddRuleTask(sendObject)
                Carousel.ajaxManager.push(task.regName, task.options, null, true);
                Carousel.ajaxManager.startLoad();
            }
        }

        return {
            ruleDel: ruleDel,
            ruleAdd: ruleAdd
        }
    })()

    Carousel.Grid = (function () {
        var ruleSelectElement = null;

        function fillRuleListGrid() {
            $("#ruleList").clearGridData();
            $("#ruleList").setGridParam({page: 1, url: Carousel.urlConfig.carouselRuleListUrl, loadtext: '加载中...',
                loadui: "block", postData: {fatherId: Carousel.memo.fatherId}}).trigger("reloadGrid");
        }

        function getLastSelectElement() {
            return ruleSelectElement
        }

        function clearRuleView() {
            ruleSelectElement = null;
        }

        function checkTotalAndActual() {
            var actualNum = $("input[name=actualNum]").val();
            var totalNum = $("input[name=totalNum]").val();
            $("input[name=check_follow]").removeAttr("checked");
            $("input[name=check_repeat]").removeAttr("checked");
            $("input[name=check_follow]").attr("disabled", "disabled");
            $("input[name=check_repeat]").attr("disabled", "disabled");
            if (actualNum === "") {
                showTips({content: "奇谱没有相应数据"});
                return;
            }
            if (actualNum == totalNum) {
                $("input[name=check_repeat]").removeAttr("disabled");
            } else {
                $("input[name=check_follow]").removeAttr("disabled");
            }
        }

        function fillRuleView(element) {
            ruleSelectElement = element;
            if (element.totalNum > 0) {
                $("input[name=totalNum]").val(element.totalNum);
            }

            $("#loadLegoMessage").dialog("open");
            queryTotalNum(element.entityId, function () {
                $("#loadLegoMessage").dialog("close");
                if (element.totalNum == 0) {
                    element.totalNum = parseInt($("input[name=actualNum]").val(), 10);
                    $("input[name=totalNum]").val($("input[name=actualNum]").val());
                }
                checkTotalAndActual();
                console.log("填充数据完成");
            });
        }

        function queryTotalNum(entityId, handler) {
            var params = Carousel.Dao.getSearchParamsBySettings();
            params["filter_EQL_albumId"] = entityId;
            params["filter_GTL_qipuId"] = 0;
            params["filter_GEL_duration"] = 60000;
            params["filter_EQI_contentType"] = 1;
            params["t"] = 0;
            params["page.order"] = "asc,asc";
            params["page.orderBy"] = "videoOrder,createTime";
            params["page.pageSize"] = 50;
            params["page.pageNo"] = 1;

            QueryComponent = {
                referElement: ruleSelectElement,
                totalCount: 0,
                params: params,
                query: function (entityId) {
                    var self = this;
                    var requestData = {url: Carousel.Constant.thirdUrl_apis_search_area_url, type: "get",
                        params: self.params,
                        needCookie: true};
                    var options = {
                        url: Carousel.urlConfig.redirect,
                        type: "post",
                        dataType: "json",
                        data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    }
                    $.ajax({
                        type: options.type,
                        url: options.url,
                        dataType: options.dataType,
                        beforeSend: function (request) {
                            request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                        },
                        data: options.data,
                        success: function (data) {
                            self.totalCount += data.data.result.length;
                            if (true === data.data.hasNext) {
                                self.params["page.pageNo"] = data.data.nextPage;
                                self.query(entityId);
                            } else {
                                $("input[name=actualNum]").val(self.totalCount);
                                if (handler != null) {
                                    handler();
                                }

                            }
                        },
                        error: function (data) {
                            showTips({
                                content: "请求失败",
                                type: "error"
                            })
                            $("input[name=actualNum]").val(0);
                        }});
                }
            };
            QueryComponent.query(entityId);
        }

        function tranDurationFormat(duration) {
            var darArr = [];
            darArr.push(duration % 60);
            duration = ( duration - duration % 60) / 60;
            if (duration > 0) {
                darArr.push(duration % 60);
            }
            duration = ( duration - duration % 60) / 60;
            if (duration > 0) {
                darArr.push(duration % 24);
            }
            duration = ( duration - duration % 24) / 24;
            if (duration > 0) {
                darArr.push(duration);
            }
            var retValue = "";
            switch (darArr.length) {
                case 4:
                    retValue = darArr[3] + "天";
                case 3:
                    retValue += darArr[2] + "时";
                case 2:
                    retValue += darArr[1] + "分";
                case 1:
                    retValue += darArr[0] + "秒";
                    break;
            }
            return retValue;
        }

        function checkIllegal(rowObject) {
            if (rowObject.status == 0) {
                return true;
            }
            return false;
        }

        function wrapRed(original) {
            return "<span style='color: red'>" + original + "</span>"
        }

        function mySelectedHandler(event) {
            var checkedFlag1 = $(event.currentTarget).prop("checked") == true;
            var _jqGrid = $("#ruleList");
            var dataOriginl = _jqGrid.jqGrid("getRowData");
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            var checkBoxArr = _jqGrid.find("input[type=checkbox][name^=jqg_ruleList_]");
            $.each(checkBoxArr, function (i, element) {
                var hiddenData = JSON.parse(dataOriginl[i].hiddenData);
                if ($(element).prop("disabled") != true && $(element).prop("checked") != checkedFlag1) {
                    _jqGrid.setSelection(hiddenData.id, checkedFlag1);
                }
            });
            $(event.currentTarget).prop("checked", checkedFlag1)
        }

        function checkSelectAble() {
            var _jqGrid = $("#ruleList");
            var dataOriginl = _jqGrid.jqGrid("getRowData");
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            var target = $("#cb_ruleList");
            target.unbind();
            target.bind("click", mySelectedHandler);
            $.each(dataOriginl, function (i, element) {
                var hiddenData = JSON.parse(element.hiddenData);
                if (hiddenData.expired === 0) {
                    _jqGrid.find("input[type=checkbox][name=jqg_ruleList_" + hiddenData.id + "]").prop("disabled", "disabled");
                    // $("#"+element.id).prop("disabled", "disabled");
                    //   _jqGrid.find("input[type=checkbox][name=jqg_list_"+element.id+"]").parent().find("td[aria-describedby=list_index]").unbind();
                }

            });
        }

        function initRuleListGrid() {
            var _jqGrid = $("#ruleList").jqGrid({
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                loadComplete: function () {
                    checkSelectAble();
                },
                beforeSelectRow: function (rowid, e) {
                    if (e.target.localName === 'input') {
                        return true;
                    }
                },

                multiselect: true,
                mtype: "post",
                datatype: "json",
                width: 1380,
                height: 450,
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                rowNum: 20,
                caption: "规则列表",
                colNames: ["奇谱ID", "显示名称", "频道", "状态", "付费", "开始时间", "结束时间", "类型", "跟播", "连播", "循环播放", "当前", "总集数", "到期", "操作", "隐藏数据"],
                colModel: [
                    {
                        name: "qipuId",
                        index: 'qipuId',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var plusUrl = Carousel.urlConfig.getQiPuBaseUrl(rowObject.qipuId);
                            return "<a target='_blank' href='" + plusUrl + "'>" + rowObject.qipuId + "</a>";
                        }
                    }
                    ,
                    {
                        name: "showName",
                        index: 'showName',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (rowObject.pageUrl != null && rowObject.pageUrl.length > 0) {
                                return "<a target='_blank' href='" + rowObject.pageUrl + "'>" + cellvalue + "</a>"
                            }
                            return cellvalue;
                        }
                    },
                    {
                        name: "channelTag",
                        index: 'channelTag',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center"
                    }
                    ,
                    {
                        name: "publishStatus",
                        index: 'publishStatus',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        //1：未发布 2：已发布)
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue == 1) {
                                return "未发布";
                            } else if (cellvalue == 2) {
                                return  "已发布";
                            } else {
                                return "未知数值：" + cellvalue;
                            }
                        }
                    },
                    {
                        name: "bossStatus",
                        index: 'bossStatus',
                        title: false,
                        width: 60,
                        sortable: false,
                        align: "center",
                        //(1：免费 2：收费)
                        formatter: function (cellvalue, options, rowObject) {
                            if (rowObject.qipuId % 100 == 2) {
                                return "";
                            }
                            if (cellvalue == 1) {
                                return "免费";
                            } else if (cellvalue == 2) {
                                return  "收费";
                            }
                        }
                    },
                    {
                        name: "startTime",
                        index: 'startTime',
                        title: false,
                        width: 160,
                        sortable: false,
                        align: "center"
                    },
                    {
                        name: "endTime",
                        index: 'endTime',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (rowObject.repeatedStatus == 1) {
                                return "------";
                            }
                            return cellvalue.substr(0, 10);
                        }
                    },
                    {
                        name: "type",
                        index: 'type',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (rowObject.qipuId % 100 == 1) {
                                return "专辑"
                            } else if (rowObject.qipuId % 100 == 2) {
                                return "播单"
                            }
                        }
                    },
                    {
                        name: "followedStatus",
                        index: 'followedStatus',
                        title: false,
                        width: 60,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue == 1) {
                                return "是";
                            } else if (cellvalue == 2) {
                                return "否";
                            }
                        }
                    },
                    {
                        name: "followNum",
                        index: 'followNum',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center"
                    },
                    {
                        name: "repeatedStatus",
                        index: 'repeatedStatus',
                        title: false,
                        width: 60,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue == 1) {
                                return "是";
                            } else if (cellvalue == 2) {
                                return "否";
                            }
                        }
                    },
                    {
                        //当前
                        index: 'currentDisplay',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var clientTime = new Date(rowObject.startTime.replace(/-/g, "/"));
                            var serverTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                            serverTime.setSeconds(0);
                            serverTime.setMinutes(0);
                            serverTime.setHours(0);
                            serverTime.setMilliseconds(0);
                            clientTime.setSeconds(0);
                            clientTime.setMinutes(0);
                            clientTime.setHours(0);
                            clientTime.setMilliseconds(0);
                            if (rowObject.totalNum == 0 || serverTime.getTime() < clientTime.getTime()) {
                                return "";
                            }
                            var minusDay = ( serverTime.getTime() - clientTime.getTime()) / 86400000;
                            var startRuleNum = minusDay * rowObject.followNum + rowObject.startNum;
                            var repeatFlag = rowObject.repeatedStatus == 1 && rowObject.totalNum == rowObject.actualNum
                            if (repeatFlag) {
                                while (startRuleNum > rowObject.totalNum) {
                                    startRuleNum -= rowObject.totalNum;
                                }
                            }
                            if (startRuleNum > rowObject.totalNum) {
                                return ""
                            }
                            var retArr = [];
                            for (var i = 0; i < rowObject.followNum; i++) {
                                if (startRuleNum + i > rowObject.totalNum) {
                                    if (repeatFlag) {
                                        startRuleNum -= rowObject.totalNum;
                                    } else {
                                        break;
                                    }
                                }
                                retArr.push(startRuleNum + i);
                            }
                            return retArr.join(",");
                        }
                    },
                    {
                        //总集数
                        name: "totalNum",
                        index: 'totalNum',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center"
                    },
                    {
                        //到期时间
                        //  name: "copyrightEndTime",
                        index: 'rest',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (rowObject.repeatedStatus == 1) {
                                return "------";
                            }
                            var checkTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                            var clientTime = new Date(rowObject.endTime.replace(/-/g, "/"));
                            checkTime.setSeconds(0);
                            checkTime.setMinutes(0);
                            checkTime.setHours(0);
                            checkTime.setMilliseconds(0);
                            clientTime.setSeconds(0);
                            clientTime.setMinutes(0);
                            clientTime.setHours(0);
                            clientTime.setMilliseconds(0);
                            var minusDay = (clientTime.getTime() - checkTime.getTime() ) / 86400000 + 1;
                            if (minusDay <= 0) {
                                return "结束";
                            } else if (minusDay < 4) {
                                return "<span style='color: red'>" + minusDay + "天</span>"
                            } else {
                                return minusDay + "天"
                            }

                        }
                    },
                    {
                        //操作
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            return "<a href='#' onclick='Carousel.Operation.ruleDel(" + rowObject.id + "," + rowObject.fatherId + ",false)'>删除</a>  ";
                        }
                    },
                    {
                        name: "hiddenData",
                        index: "hiddenData",
                        title: false,
                        hidden: true,
                        formatter: function (cellvalue, options, rowObject) {
                            var expired = 0;
                            if (rowObject.repeatedStatus != 1) {
                                var checkTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                                var clientTime = new Date(rowObject.endTime.replace(/-/g, "/"));
                                checkTime.setSeconds(0);
                                checkTime.setMinutes(0);
                                checkTime.setHours(0);
                                checkTime.setMilliseconds(0);
                                clientTime.setSeconds(0);
                                clientTime.setMinutes(0);
                                clientTime.setHours(0);
                                clientTime.setMilliseconds(0);
                                var minusDay = (clientTime.getTime() - checkTime.getTime() ) / 86400000 + 1;
                                if (minusDay <= 0) {
                                    expired = 1;
                                }
                            }

                            var data = {};
                            data.id = rowObject.id;
                            data.fatherId = rowObject.fatherId;
                            data.expired = expired;
                            return JSON.stringify(data);
                        }
                    }
                ],
                pager: "#pagerAutoRule"
            });

            _jqGrid.jqGrid('navGrid', "#pagerAutoRule", {
                edit: false,
                add: false,
                del: false,
                search: false,
                refresh: false
            });
            _jqGrid.jqGrid('navButtonAdd', "#pagerAutoRule", {
                caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                onClickButton: function () {
                    var gridElement = $("#ruleList");
                    var dataOriginl = gridElement.jqGrid("getRowData");
                    var hiddenData = JSON.parse(dataOriginl[0].hiddenData);
                    var fatherId = hiddenData.fatherId;
                    var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                    var ids = [];
                    $.each(selectedtrArr, function (i, element) {
                        ids.push(parseInt($(element).attr("id")));
                    });

                    if (ids.length == 0) {
                        return;
                    }
                    //Carousel.Operation.programBatchDel(ids);
                    Carousel.Operation.ruleDel(ids.join(','), fatherId, "是否确认删除本页内所有已选择的过期规则？删除后不可恢复");
                }, position: "last", title: "批量删除", cursor: "pointer"
            });
        }


        function initGrid() {
            initRuleListGrid();
        }

        return {
            initGrid: initGrid,
            fillRuleListGrid: fillRuleListGrid,
            fillRuleView: fillRuleView,
            clearRuleView: clearRuleView,
            getLastSelectElement: getLastSelectElement,
            tranDurationFormat: tranDurationFormat
        }
    })();
})

$(document).ready(function () {
    Carousel.Suggest.initSuggest();
    Carousel.DialogManager.initDialogs();
    Carousel.EventManager.bindEvent();
    Carousel.EventManager.initDateTimePicker();
    Carousel.Grid.initGrid();
    Carousel.ajaxManager.afterLoadComplete(function () {
        var channelData = Carousel.Dao.getChannel();
        if (channelData.liveType != 3) {
            showTips({content: "当前频道不是轮播台"});
            setTimeout(function () {
                window.location.href = "/epg/program_list.html?fatherId=" + Carousel.memo.fatherId;
            }, 2000)
            return;
        }
        $("#carouselAutoRuleView").find("button[name=addRule]").bind("click", function (event) {
            Carousel.Operation.ruleAdd();
        })
        Carousel.Grid.fillRuleListGrid();
    });

    var taskArr = [];
    taskArr.push(Carousel.Task.getLiveProgramType());
    taskArr.push(Carousel.Task.platformsTask());
    taskArr.push(Carousel.Task.getPlatformReferTask());

    var fatherId = Com.url.getParameter("fatherId")
    if (fatherId != null) {
        Carousel.memo.fatherId = parseInt(fatherId);

        taskArr.push({regName: Carousel.memo.getChannel, options: {  type: "post",
            url: Carousel.urlConfig.channelGet,
            dataType: "json",
            data: {id: fatherId}}})
    }
    $.each(taskArr, function (index, element) {
        Carousel.ajaxManager.push(element.regName, element.options);
    })
    Carousel.memo.dataTime = Carousel.Formatter.quickDateFormat(new Date())
    Carousel.ajaxManager.startLoad();
})
